package com.webdrider.servlet.action.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.model.validators.ActionValidator;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.common.servlet.interfaces.IParser;
import com.webdrider.model.requests.system.GetAllSessionsRequest;
import com.webdrider.model.response.system.GetAllSessionsResponse;
import com.webdrider.model.validators.AdminValidator;
import com.webdrider.model.validators.SessionValidator;
import com.webdrider.servlet.util.RequestAction;
import com.webdrider.servlet.util.parser.system.GetAllSessionsXMLParser;
import com.webdrider.util.SessionCacheContainer;

public class GetAllSessionsServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;
	private static List<AbstractValidator> validators = new ArrayList<AbstractValidator>();
	
	private GetAllSessionsRequest requestContent;
	private GetAllSessionsXMLParser parser = new GetAllSessionsXMLParser();
	
	static {
		validators.add(new ActionValidator(RequestAction.GET_ALL_SESSIONS));
		validators.add(new SessionValidator());
		validators.add(new AdminValidator());
	}

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) {
		try {
			GetAllSessionsResponse allSessionsResponse = new GetAllSessionsResponse();
			
			allSessionsResponse.setRequestAction(requestContent.getAction());
			allSessionsResponse.setSessions(SessionCacheContainer.getAll());
			
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseResponse(allSessionsResponse));
			response.getWriter().close();
		} catch (IOException ioException) {
			error(new ParserError(ParserError.STREAM_ERROR), response);
		} catch (ParserException parserException) {
			exception(parserException, response);
		}
	}

	@Override
	public void setRequest(AbstractRequest abstractRequest) {
		requestContent = (GetAllSessionsRequest) abstractRequest;
	}

	@Override
	public List<AbstractValidator> getValidators() {
		return validators;
	}

	@Override
	public IParser parser() {
		return parser;
	}
}
